package com.ahdy.controller;

import com.ahdy.service.TencentTtsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/api/tts")
public class TtsController {

    private final TencentTtsService ttsService;

    public TtsController(TencentTtsService ttsService) {
        this.ttsService = ttsService;
    }

    /**
     * 文本转语音并保存（兼容原接口）
     * 
     * @param text       要转换的文本
     * @param voiceType  音色类型
     * @param returnFile 是否返回文件（true返回文件，false返回URL）
     * @return 音频文件或URL
     */
    @PostMapping("/synthesize")
    public ResponseEntity<?> synthesize(
            @RequestParam String text,
            @RequestParam(required = false) Long voiceType,
            @RequestParam(required = false, defaultValue = "false") boolean returnFile) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 参数验证
            if (text == null || text.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "文本不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            String cleanText = text.trim();

            // 根据文本长度选择处理方式
            if (cleanText.length() > 150) {
                response.put("success", false);
                response.put("message", String.format(
                        "文本长度超限（%d字符），单次保存最多支持150字符，请使用长文本合成接口",
                        cleanText.length()));
                response.put("suggestion", "使用 /api/tts/synthesize-long-text 接口处理长文本");
                return ResponseEntity.badRequest().body(response);
            }

            log.info("开始合成并保存，文本长度: {} 字符，音色: {}", cleanText.length(), voiceType);

            String audioUrl = ttsService.synthesizeAndSave(cleanText, voiceType);

            // 如果不需要返回文件，返回URL信息
            if (!returnFile) {
                response.put("success", true);
                response.put("audioUrl", audioUrl);
                response.put("message", "音频合成并保存成功");
                response.put("textLength", cleanText.length());
                return ResponseEntity.ok(response);
            }

            // 返回文件
            // 从URL中获取文件名
            String fileName = audioUrl.substring(audioUrl.lastIndexOf('/') + 1);
            Path path = Paths.get(ttsService.getSaveDir(), fileName);
            Resource resource = new UrlResource(path.toUri());

            if (resource.exists() || resource.isReadable()) {
                // 处理文件名编码
                String encodedFilename = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString())
                        .replaceAll("\\+", "%20");

                // 分别处理不同浏览器的文件名编码
                String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
                        encodedFilename, encodedFilename);

                return ResponseEntity.ok()
                        .contentType(MediaType.parseMediaType("audio/mpeg"))
                        .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                        .header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION)
                        .body(resource);
            } else {
                response.put("success", false);
                response.put("message", "无法读取生成的音频文件");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }

        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);

        } catch (Exception e) {
            log.error("音频合成失败", e);
            response.put("success", false);
            response.put("message", "音频合成失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 长文本语音合成（优化版）
     */
    @PostMapping("/synthesize-long-text")
    public ResponseEntity<Map<String, Object>> synthesizeLongText(
            @RequestParam String text,
            @RequestParam(required = false) Long voiceType,
            @RequestParam(required = false) Long speed) {

        Map<String, Object> response = new HashMap<>();
        long startTime = System.currentTimeMillis();

        try {
            // 参数验证
            if (text == null || text.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "文本不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            String cleanText = text.trim();

            if (cleanText.length() > 50000) {
                response.put("success", false);
                response.put("message", "文本长度不能超过50000字符，当前长度: " + cleanText.length());
                return ResponseEntity.badRequest().body(response);
            }

            log.info("开始长文本合成，文本长度: {} 字符，音色: {}，语速: {}",
                    cleanText.length(), voiceType, speed);

            // 使用优化的长文本处理，带进度日志
            String base64Audio = ttsService.synthesizeLongTextToBase64(cleanText, voiceType, speed,
                    progressInfo -> {
                        log.info("长文本处理进度: {}", progressInfo);
                    });

            long duration = System.currentTimeMillis() - startTime;

            response.put("success", true);
            response.put("audioData", base64Audio);
            response.put("message", "长文本音频合成成功");
            response.put("textLength", cleanText.length());
            response.put("audioSize", base64Audio.length());
            response.put("processingTime", duration);

            log.info("长文本合成完成，耗时: {} ms，音频大小: {} bytes",
                    duration, base64Audio.length());

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);

        } catch (Exception e) {
            long duration = System.currentTimeMillis() - startTime;
            log.error("长文本合成失败，耗时: {} ms", duration, e);
            response.put("success", false);
            response.put("message", "长文本合成失败: " + e.getMessage());
            response.put("processingTime", duration);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 文本转语音返回Base64编码（兼容原接口）
     */
    @PostMapping("/synthesize-base64")
    public ResponseEntity<Map<String, Object>> synthesizeBase64(
            @RequestParam String text,
            @RequestParam(required = false) Long voiceType,
            @RequestParam(required = false) Long speed) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 参数验证
            if (text == null || text.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "文本不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            String cleanText = text.trim();

            if (cleanText.length() > 150) {
                response.put("success", false);
                response.put("message", String.format(
                        "单次请求文本长度不能超过150字符，当前长度: %d，请使用长文本合成接口",
                        cleanText.length()));
                response.put("suggestion", "使用 /api/tts/synthesize-long-text 接口");
                return ResponseEntity.badRequest().body(response);
            }

            log.info("开始Base64合成，文本长度: {} 字符", cleanText.length());

            String base64Audio = ttsService.synthesizeToBase64(cleanText, voiceType, speed);

            response.put("success", true);
            response.put("audioData", base64Audio);
            response.put("message", "音频合成成功");
            response.put("textLength", cleanText.length());
            response.put("audioSize", base64Audio.length());

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);

        } catch (Exception e) {
            log.error("Base64合成失败", e);
            response.put("success", false);
            response.put("message", "音频合成失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 批量文本转语音（文件上传，兼容原接口）
     */
    @PostMapping("/batch-synthesize")
    public ResponseEntity<Map<String, Object>> batchSynthesize(
            @RequestParam("file") MultipartFile file,
            @RequestParam(required = false) Long voiceType,
            @RequestParam(required = false) Long speed) {

        Map<String, Object> response = new HashMap<>();
        long startTime = System.currentTimeMillis();

        try {
            // 文件验证
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "上传文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !originalFilename.toLowerCase().endsWith(".txt")) {
                response.put("success", false);
                response.put("message", "只支持.txt格式的文本文件");
                return ResponseEntity.badRequest().body(response);
            }

            // 读取文件内容
            StringBuilder textBuilder = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    textBuilder.append(line).append("\n");
                }
            }

            String text = textBuilder.toString().trim();

            if (text.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件内容为空");
                return ResponseEntity.badRequest().body(response);
            }

            if (text.length() > 50000) {
                response.put("success", false);
                response.put("message", "文件内容过长，不能超过50000字符，当前长度: " + text.length());
                return ResponseEntity.badRequest().body(response);
            }

            log.info("开始批量处理文件: {}，文本长度: {} 字符", originalFilename, text.length());

            // 使用长文本合成处理
            String base64Audio = ttsService.synthesizeLongTextToBase64(text, voiceType, speed,
                    progressInfo -> {
                        log.debug("批量处理进度: {}", progressInfo);
                    });

            long duration = System.currentTimeMillis() - startTime;

            response.put("success", true);
            response.put("audioData", base64Audio);
            response.put("message", "批量处理完成");
            response.put("fileName", originalFilename);
            response.put("textLength", text.length());
            response.put("audioSize", base64Audio.length());
            response.put("processingTime", duration);

            log.info("批量处理完成，文件: {}，耗时: {} ms", originalFilename, duration);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            long duration = System.currentTimeMillis() - startTime;
            log.error("批量处理失败，耗时: {} ms", duration, e);
            response.put("success", false);
            response.put("message", "批量处理失败: " + e.getMessage());
            response.put("processingTime", duration);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 获取服务状态和配置信息
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getStatus() {
        Map<String, Object> response = new HashMap<>();

        response.put("success", true);
        response.put("service", "Tencent TTS Service");
        response.put("version", "2.0.0 - Multi-text Optimized");
        response.put("status", "running");
        response.put("timestamp", System.currentTimeMillis());

        Map<String, Object> limits = new HashMap<>();
        limits.put("singleRequestMaxLength", 150);
        limits.put("longTextMaxLength", 50000);
        limits.put("optimalSegmentLength", 120);
        limits.put("batchFileMaxLength", 50000);
        response.put("limits", limits);

        Map<String, String> endpoints = new HashMap<>();
        endpoints.put("synthesize", "POST /synthesize - 短文本合成并保存文件");
        endpoints.put("synthesizeBase64", "POST /synthesize-base64 - 短文本合成返回Base64");
        endpoints.put("synthesizeLongText", "POST /synthesize-long-text - 长文本智能分割合成");
        endpoints.put("batchSynthesize", "POST /batch-synthesize - 批量文件处理");
        endpoints.put("status", "GET /status - 获取服务状态");
        response.put("endpoints", endpoints);

        Map<String, String> recommendations = new HashMap<>();
        recommendations.put("shortText", "≤150字符使用 /synthesize-base64");
        recommendations.put("longText", ">150字符使用 /synthesize-long-text");
        recommendations.put("fileUpload", "文件上传使用 /batch-synthesize");
        recommendations.put("enhanced", "高级功能使用 /api/enhanced-tts/ 接口");
        response.put("recommendations", recommendations);

        return ResponseEntity.ok(response);
    }

    /**
     * 测试端点
     */
    @GetMapping("/test")
    public ResponseEntity<Map<String, Object>> test() {
        Map<String, Object> response = new HashMap<>();

        try {
            // 1. 测试目录创建
            Path audioDir = Paths.get(ttsService.getSaveDir()).toAbsolutePath();
            boolean dirExists = Files.exists(audioDir);
            boolean dirWritable = Files.isWritable(audioDir);

            response.put("audioDir", audioDir.toString());
            response.put("dirExists", dirExists);
            response.put("dirWritable", dirWritable);

            // 2. 测试文件创建
            String testText = "测试文本";
            String audioUrl = ttsService.synthesizeAndSave(testText, null);

            response.put("testText", testText);
            response.put("audioUrl", audioUrl);

            // 3. 测试文件访问
            String fileName = audioUrl.substring(audioUrl.lastIndexOf('/') + 1);
            Path audioFile = audioDir.resolve(fileName);
            boolean fileExists = Files.exists(audioFile);
            long fileSize = fileExists ? Files.size(audioFile) : -1;

            response.put("audioFile", audioFile.toString());
            response.put("fileExists", fileExists);
            response.put("fileSize", fileSize);

            response.put("success", true);
            response.put("message", "测试完成");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("测试失败", e);
            response.put("success", false);
            response.put("error", e.getMessage());
            response.put("stackTrace", e.getStackTrace());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}
